package android_testsuite.mytest.network_test;

import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;

import java.io.IOException;
import java.lang.ref.WeakReference;

/**
 * HTTP请求类
 * @author Ren Hui
 * @since 1.0.1.058
 */
public class HttpRunnable implements Runnable {
    private String mUrl;
    private HttpClient mHttpClient;
    private WeakReference<HttpActivity> mActivityWeakReference;

    public HttpRunnable(HttpActivity activity, String url) {
        super();
        this.mUrl = url;
        this.mActivityWeakReference = new WeakReference<HttpActivity>(activity);
    }

    // 显示信息
    public void showLogMsg(String msg) {
        final HttpActivity activity = mActivityWeakReference.get();
        if (activity != null) {
            activity.onLogging(msg);
        }
    }

    @Override
    public void run() {
        String url = mUrl.toLowerCase();
        this.mHttpClient = getHttpClient();
        HttpGet get = new HttpGet(url);
        HttpResponse response;
        try {
            response = this.mHttpClient.execute(get);
            if (response == null) {
                return;
            }
            //获取状态行中的状态码。
            int statusCode = response.getStatusLine().getStatusCode();
            // HTTP 200 OK  200表示请求成功
            if (statusCode == 200) {
                showLogMsg("Succeed, content length:"
                        + response.getEntity().getContentLength() + "\n");
            } else {
                showLogMsg("Response:" + statusCode);
            }
        } catch (ClientProtocolException e) {
            showLogMsg(e.getMessage() + "\n");
        } catch (IOException e) {
            showLogMsg(e.getMessage() + "\n");
        } catch (Exception e) {
            showLogMsg(e.getMessage() + "\n");
        } finally {
            close();
        }
    }

    /**
     * 关闭HTTP链接的方法
     */
    public void close() {
        ClientConnectionManager ccm = mHttpClient.getConnectionManager();
        if (ccm != null) {
            // 首先先关闭过期的连接
            ccm.closeExpiredConnections();
            // 关闭所有的链接，释放资源
            ccm.shutdown();
        }

    }

    // 获取支持Https和HTTP的HttpClient的方法
    public synchronized HttpClient getHttpClient() {
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
        HttpProtocolParams.setUseExpectContinue(params, true);
        // 设置连接管理器的超时
        ConnManagerParams.setTimeout(params, 10000);
        // 设置连接超时
        HttpConnectionParams.setConnectionTimeout(params, 10000);
        // 设置socket超时
        HttpConnectionParams.setSoTimeout(params, 10000);
        SchemeRegistry schReg = new SchemeRegistry();
        // 设置https的支持
        schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
        //设置HTTP支持
        schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        ClientConnectionManager conManager = new ThreadSafeClientConnManager(params, schReg);
        HttpClient httpClient = new DefaultHttpClient(conManager, params);
        return httpClient;
    }
}